package com.moji.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.moji.common.entity.MyPage;
import com.moji.common.utils.DateUtils;
import com.moji.common.utils.HttpUtils;
import com.moji.common.utils.PageUtil;
import com.moji.entity.*;
import com.moji.entity.dto.AddOrderDto;
import com.moji.entity.dto.MojiMiYaoDto;
import com.moji.entity.dto.QueryOrderDto;
import com.moji.entity.vo.FinanceOrderVo;
import com.moji.entity.vo.MijiMoYaoVo;
import com.moji.entity.vo.MijiMoYaoVo1;
import com.moji.entity.vo.OrderVo;
import com.moji.mapper.MjOrderMapper;
import com.moji.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moji.util.IdGenerator;
import com.moji.util.MoJiCommonUtils;
import com.moji.util.poi.ExcelUtil;
import org.apache.http.util.TextUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author ccl
 * @since 2024-07-27
 */
@Service
public class MjOrderServiceImpl extends ServiceImpl<MjOrderMapper, MjOrder> implements MjOrderService {

    @Resource
    private MjOrderDetailService mjOrderDetailService;

    @Resource
    private MjFlowConfigService mjFlowConfigService;

    @Resource
    private MjFlowService mjFlowService;

    @Resource
    private SysMessageService sysMessageService;

    @Resource
    private DataDictionaryService dataDictionaryService;

    @Resource
    private MjUserService mjUserService;

    @Resource
    private MjCompanyInfoService mjCompanyInfoService;

    @Resource
    private IdGenerator idGenerator;

    @Resource
    private  GdAreaService gdAreaService;
    @Override
    public MyPage<MjOrder> queryByPage(QueryOrderDto dto) {
            LambdaQueryWrapper<MjOrder> wrapper = new LambdaQueryWrapper<>();
            //手机号
            wrapper.like(ObjectUtil.isNotEmpty(dto.getMobile()), MjOrder::getMobile
                , dto.getMobile());
        //用户ID
        wrapper.like(ObjectUtil.isNotEmpty(dto.getUserCode()), MjOrder::getUserCode
                , dto.getUserCode());
        //订单号
        wrapper.like(ObjectUtil.isNotEmpty(dto.getOrderCode()), MjOrder::getOrderCode
                , dto.getOrderCode());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getOrderName()), MjOrder::getOrderName
                , dto.getOrderName());
        //订单状态
        if(ObjectUtil.isNotEmpty(dto.getOrderStatus()) && 5==dto.getOrderStatus()){
            //改价拒绝数据筛选
            wrapper.eq(MjOrder::getOrderStatus, 0);
            wrapper.eq(MjOrder::getAuditStatus, 22);
        }else if(ObjectUtil.isNotEmpty(dto.getOrderStatus())){
            wrapper.eq(MjOrder::getOrderStatus
                    , dto.getOrderStatus());
        }

        //姓名
        wrapper.like(ObjectUtil.isNotEmpty(dto.getUserName()), MjOrder::getUserName
                , dto.getUserName());
        //账户类型
        if(ObjectUtil.isNotEmpty(dto.getAccountType()))
        {
            if("0".equals(dto.getAccountType()))
            {
                wrapper.eq(MjOrder::getAccountType
                        , "个人账户");
            }
            else if("1".equals(dto.getAccountType()))
            {
                wrapper.eq(MjOrder::getAccountType
                        , "企业账户");
            }

        }

        //企业名称
        wrapper.like(ObjectUtil.isNotEmpty(dto.getCompanyName()), MjOrder::getCompanyName
                , dto.getCompanyName());
        //订单原金额
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getOriginalAmount()), MjOrder::getOriginalAmount
                , dto.getOriginalAmount());
        //订单时间
        if(ObjectUtil.isNotEmpty(dto.getOrderTime()))
        {
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(dto.getOrderTime());
            String startDate=dateStr+" 00:00:00";
            String endDate=dateStr+" 23:59:59";
            wrapper.ge( MjOrder::getOrderTime
                    , startDate);
            wrapper.le( MjOrder::getOrderTime
                    , endDate);
        }

        //支付方式
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getPayType()), MjOrder::getPayType
                , dto.getPayType());
        //支付方式
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getBillStatus()), MjOrder::getBillStatus
                , dto.getBillStatus());
        //创建时间倒叙
        wrapper.orderByDesc(MjOrder::getCreateTime);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<MjOrder> mjOrders = list(wrapper);
        PageInfo<MjOrder> info = new PageInfo<>(mjOrders);
        return PageUtil.PageInfo2MyPage(info);
    }

    @Override
    public boolean delete(Long id) {
        MjOrder mjOrder = this.getById(id);
        if (mjOrder == null) {
            throw new RuntimeException("主键ID不能为空,请核查!");
        }
        LambdaQueryWrapper<MjOrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjOrderDetail::getOrderMxCode, mjOrder.getOrderCode());
        mjOrderDetailService.remove(wrapper);

        return this.removeById(id);
    }

    @Override
    public boolean add(AddOrderDto addOrderDto) {
        MjOrder mjOrder = new MjOrder();
        BeanUtils.copyProperties(addOrderDto, mjOrder);
        String orderCode = idGenerator.idGenerator("DD");
        mjOrder.setOrderCode(orderCode);
        mjOrder.setNewOrderAmount(addOrderDto.getOrderAmount());
        mjOrder.setCreateId(MoJiCommonUtils.getUserCode());
        mjOrder.setUpdateId(MoJiCommonUtils.getUserCode());
        mjOrder.setCreateTime(new Date());
        mjOrder.setUpdateTime(new Date());

        if (ObjectUtil.isEmpty(addOrderDto.getOrderDetailList())) {
            throw new RuntimeException("订单明细不存在,请核查!");
        }
        addOrderDto.getOrderDetailList().forEach(item -> {
            String detailCode = idGenerator.idGenerator("DDMX");
            item.setOrderCode(orderCode);
            item.setOrderMxCode(detailCode);
            item.setCreateId(MoJiCommonUtils.getUserCode());
            item.setUpdateId(MoJiCommonUtils.getUserCode());
            item.setCreateTime(new Date());
            item.setUpdateTime(new Date());
            mjOrderDetailService.save(item);
        });
        return this.save(mjOrder);
    }

    @Override
    public boolean edit(AddOrderDto addOrderDto) {
        MjOrder mjOrder = this.getById(addOrderDto.getId());
        BeanUtils.copyProperties(addOrderDto, mjOrder);
        mjOrder.setUpdateId(MoJiCommonUtils.getUserCode());
        mjOrder.setUpdateTime(new Date());
        if (ObjectUtil.isEmpty(addOrderDto.getOrderDetailList())) {
            throw new RuntimeException("订单明细不存在,请核查!");
        }
        //删除旧的明细
        LambdaQueryWrapper<MjOrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjOrderDetail::getOrderCode, addOrderDto.getOrderCode());
        mjOrderDetailService.remove(wrapper);
        addOrderDto.getOrderDetailList().forEach(item -> {
            String detailCode = idGenerator.idGenerator("DDMX");
            item.setOrderCode(addOrderDto.getOrderCode());
            item.setOrderMxCode(detailCode);
            item.setCreateId(MoJiCommonUtils.getUserCode());
            item.setUpdateId(MoJiCommonUtils.getUserCode());
            item.setCreateTime(new Date());
            item.setUpdateTime(new Date());
            mjOrderDetailService.save(item);
        });
        return this.updateById(addOrderDto);
    }

    @Override
    public OrderVo detail(Long id) {
        OrderVo orderVo = new OrderVo();
        MjOrder mjOrder = this.getById(id);
        if (mjOrder == null) {
            throw new RuntimeException("订单数据不存在,请核查!");
        }
        BeanUtils.copyProperties(mjOrder, orderVo);

        LambdaQueryWrapper<MjOrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjOrderDetail::getOrderCode, mjOrder.getOrderCode());
        List<MjOrderDetail> detailList = mjOrderDetailService.list(wrapper);
        detailList.forEach(mjOrderDetail->{
            //服务到期时间
            if (ObjectUtil.isNotEmpty(mjOrderDetail.getServiceTimeCode())) {
                if ("N1Y".equals(mjOrderDetail.getServiceTimeCode())) {
                    if (mjOrderDetail.getEffectTime() != null) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(mjOrderDetail.getEffectTime());
                        calendar.add(Calendar.YEAR, 1);
                        mjOrderDetail.setExpirationTime(calendar.getTime());
                    }
                } else if ("N2Y".equals(mjOrderDetail.getServiceTimeCode())) {
                    {
                        if (mjOrderDetail.getEffectTime() != null) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(mjOrderDetail.getEffectTime());
                            calendar.add(Calendar.YEAR, 2);
                            mjOrderDetail.setExpirationTime(calendar.getTime());
                        }
                    }

                } else if ("T7D".equals(mjOrderDetail.getServiceTimeCode())) {
                    if (mjOrderDetail.getEffectTime() != null) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(mjOrderDetail.getEffectTime());
                        calendar.add(Calendar.DAY_OF_MONTH, 7);
                        mjOrderDetail.setExpirationTime(calendar.getTime());
                    }
                }
            }
        });
        orderVo.setOrderDetailList(detailList);

        //用户信息
        MjUser mjUser=mjUserService.getOne(new LambdaQueryWrapper<MjUser>()
        .eq(MjUser::getUserCode,mjOrder.getUserCode()));
        if(mjUser !=null){
            orderVo.setEmail(mjUser.getEmail());
            orderVo.setRegisterTime(mjUser.getCreateTime());
            orderVo.setCompanyCode(mjUser.getCompanyCode());
            orderVo.setCompanyName(mjUser.getCompanyName());
        }
        if("企业账户".equals(mjOrder.getAccountType())){
            MjCompanyInfo mjCompanyInfo=mjCompanyInfoService.getOne(new LambdaQueryWrapper<MjCompanyInfo>()
                    .eq(MjCompanyInfo::getCompanyCode,mjUser.getCompanyCode()));
            if(mjCompanyInfo !=null){
                String companyAddress = mjCompanyInfo.getCompanyAddress();
                StringBuilder stringBuilder=new StringBuilder();
                if(companyAddress.split(",")!=null&&companyAddress.split(",").length>0)
                {
                    String[] split = companyAddress.split(",");

                    for (int i = 0; i < split.length; i++) {
                        LambdaQueryWrapper<GdArea> wrapper1 = new LambdaQueryWrapper<>();
                        wrapper1.eq(GdArea::getAreaCode,split[i]);
                        String areaName = gdAreaService.getOne(wrapper1).getAreaName();
                        stringBuilder.append(areaName);

                    }
                }


                orderVo.setCompanyAddressDetail(mjCompanyInfo.getCompanyAddressDetail());
                orderVo.setCompanyAddress(stringBuilder.toString());
            }
        }
        return orderVo;
    }

    @Override
    public boolean editAmount(Long id, String amount) {
        MjOrder mjOrder = this.getById(id);
        if (mjOrder == null) {
            throw new RuntimeException("订单数据不存在,请核查!");
        }
        if (ObjectUtil.isEmpty(amount)) {
            throw new RuntimeException("修改金额不能为空,请核查!");
        }
        if(mjOrder.getAuditStatus() !=null && mjOrder.getAuditStatus()==21){
            throw new RuntimeException("已修改过金额，不能再修改,请核查!");
        }
        MjFlow mjFlowOld = mjFlowService.getOne(new LambdaQueryWrapper<MjFlow>()
                .eq(MjFlow::getProductCode, mjOrder.getProductCode())
                .eq(MjFlow::getOrderCode, mjOrder.getOrderCode())
                .eq(MjFlow::getAuditStatus,20));
        if (mjFlowOld != null) {
            throw new RuntimeException("该产品下的订单修改金额已处于审核中,无法再次编辑,请核查!");
        }
        //向审批列表新增数据
        MjFlow mjFlow = new MjFlow();
        mjFlow.setFlowName("调整金额");
        mjFlow.setProductCode(mjOrder.getProductCode());
        mjFlow.setProductType(mjOrder.getProductType());
        mjFlow.setProductName(mjOrder.getProductName());
        mjFlow.setOrderCode(mjOrder.getOrderCode());
        mjFlow.setOrdertName(mjOrder.getOrderName());
        mjFlow.setOrderAmount(mjOrder.getOrderAmount());
        mjFlow.setNewOrderAmount(mjOrder.getNewOrderAmount());
        mjFlow.setEditOrderAmount(new BigDecimal(amount));
        //审核状态10 - 未提交 11 - 已提交
        mjFlow.setSubmitStatus(11);
        mjFlow.setSubmitTime(new Date());
        mjFlow.setSubmitCode(MoJiCommonUtils.getUserCode());
        mjFlow.setSubmitName(MoJiCommonUtils.getUserName());
        //审核状态 20 - 审核中 21-已审核 22-已驳回
        mjFlow.setAuditStatus(20);
        mjFlow.setCreateId(MoJiCommonUtils.getUserCode());
        mjFlow.setUpdateId(MoJiCommonUtils.getUserCode());
        mjFlow.setCreateTime(new Date());
        mjFlow.setUpdateTime(new Date());
        //记录审核流转节点
        mjFlow.setSpareInt1(1);
        //流程类型
        mjFlow.setFlowType("2");
        mjFlow.setFlowName("调整金额");
        mjFlowService.add(mjFlow);

        //审核状态20 - 审核中 21-已审核 22-已驳回
        mjOrder.setAuditStatus(20);

        return this.updateById(mjOrder);
    }

    @Override
    public boolean cancel(Long id) {
        MjOrder mjOrder = this.getById(id);
        if (mjOrder == null) {
            throw new RuntimeException("订单数据不存在,请核查!");
        }
        //审核状态 20 - 审核中 21-已审核 22-已驳回
        mjOrder.setAuditStatus(null);
        return this.updateById(mjOrder);
    }

    @Override
    public boolean shenhe(Long id) {
        MjOrder mjOrder = this.getById(id);
        if (mjOrder == null) {
            throw new RuntimeException("订单数据不存在,请核查!");
        }
        //审核状态
        mjOrder.setOrderStatus(1);
        mjOrder.setPayAmount(mjOrder.getOrderAmount());
        mjOrder.setPayTime(new Date());
        //获取密钥逻辑------------------------
        //根据订单号查询订单明细表，然后将订单明细得信息生成密钥
        List<MjOrderDetail> list = mjOrderDetailService.list(new LambdaQueryWrapper<MjOrderDetail>().eq(MjOrderDetail::getOrderCode, mjOrder.getOrderCode()));
        //循环获取密钥
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                MjOrderDetail mjOrderDetail = list.get(i);
                MojiMiYaoDto mojiMiYaoDto = new MojiMiYaoDto();
                mojiMiYaoDto.setOrderId(mjOrderDetail.getOrderMxCode());
                mojiMiYaoDto.setRegion(mjOrderDetail.getServiceCityCode());
                mojiMiYaoDto.setType(mjOrderDetail.getCallWayCode());
                mojiMiYaoDto.setRate(mjOrderDetail.getCallCountCode());
                mojiMiYaoDto.setDuration(mjOrderDetail.getServiceTimeCode());
                //判断支付时间，如果支付时间在生效时间之后，以支付时间为准，如果支付时间在生效时间之前，以生效时间为准
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                // 使用format方法转换Date到指定格式的字符串
                String formattedDate = sdf.format(mjOrderDetail.getEffectTime());
                mojiMiYaoDto.setValidStartTime(formattedDate);
                List<String> endpoints = new ArrayList<>();
                if (!TextUtils.isEmpty(mjOrderDetail.getWeatherTypeCode())) {
                    String[] split = mjOrderDetail.getWeatherTypeCode().split("/");
                    for (int j = 0; j < split.length; j++) {
                        endpoints.add(split[j]);
                    }
                } else {
                    String[] split = mjOrderDetail.getGlobalCityCode().split("/");
                    for (int j = 0; j < split.length; j++) {
                        endpoints.add(split[j]);
                    }
                }
                mojiMiYaoDto.setEndpoints(endpoints);
                // 创建Gson对象
                Gson gson = new Gson();
                // 将对象转换为JSON字符串
                String jsonString = gson.toJson(mojiMiYaoDto);
                String s = null;
                try {
                    s = HttpUtils.sendPostRequest("/tob-data-misc/eshop/access/creation", jsonString);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Gson gson1 = new Gson();
                MijiMoYaoVo1 mijiMoYaoVo1 = gson1.fromJson(s, MijiMoYaoVo1.class);
                if (mijiMoYaoVo1 != null && mijiMoYaoVo1.getCode() == 200) {
                    Gson gson2 = new Gson();
                    MijiMoYaoVo mijiMoYaoVo = gson2.fromJson(s, MijiMoYaoVo.class);
                    if (mijiMoYaoVo.getData().getAccess() != null && mijiMoYaoVo.getData().getAccess().getOrderId() != null) {
                        //核对订单号
                        if (mijiMoYaoVo.getData().getAccess().getOrderId().equals(mjOrderDetail.getOrderMxCode())) {
                            //将密钥更新到订单明细得springString2中
                            mjOrderDetail.setSpareString2(mijiMoYaoVo.getData().getAccess().getMdsPassword());
                            mjOrderDetail.setSpareInt2(mijiMoYaoVo.getData().getAccess().getId());
                            mjOrderDetail.setUpdateTime(new Date());
                            mjOrderDetail.setUseStatus(1);
                            mjOrderDetailService.updateById(mjOrderDetail);
                        }
                    }
                }
                else{
                    //获取墨迹密钥失败

                }


            }
        }
        //结束---------------------------
        return this.updateById(mjOrder);
    }

    @Override
    public boolean audit(Long id) {
        //流程类型：1-价格设置 2-价格调整
        MjFlowConfig mjFlowConfig = mjFlowConfigService.getOne(new LambdaQueryWrapper<MjFlowConfig>()
                .eq(MjFlowConfig::getFlowType, 2));
        if (mjFlowConfig == null) {
            throw new RuntimeException("调价规则不存在无法审核,请核查!");
        }
        MjOrder mjOrder = this.getById(id);
        if (mjOrder == null) {
            throw new RuntimeException("订单数据不存在,请核查!");
        }
        List<String> roles = Arrays.asList(mjFlowConfig.getRoleCode());
        //一级审批完成
        if (roles.size() == 1) {
            if (MoJiCommonUtils.getRoleCode().contains(mjFlowConfig.getRoleCode())) {
                mjOrder.setEditOrderAmount(null);
                mjOrder.setNewOrderAmount(mjOrder.getEditOrderAmount());
                //审核状态21 - 待审核 22 - 已审核 23-已驳回
                mjOrder.setAuditStatus(1);
                return this.updateById(mjOrder);
            } else {
                throw new RuntimeException("该用户无权限审核,请核查!");
            }
        }
        //二级审批完成
        if (roles.size() == 2) {
            if (mjOrder.getSpareInt1() == 1) {//第一次审核
                if (MoJiCommonUtils.getRoleCode().contains(roles.get(0))) {
                    mjOrder.setEditOrderAmount(null);
                    //审核状态21 - 待审核 22 - 已审核 23-已驳回
                    mjOrder.setAuditStatus(0);
                    mjOrder.setSpareInt1(2);
                    return this.updateById(mjOrder);
                } else {
                    throw new RuntimeException("该用户无权限审核,请核查!");
                }
            }
            if (mjOrder.getSpareInt1() == 2) {//第二次审核
                if (MoJiCommonUtils.getRoleCode().contains(roles.get(1))) {
                    mjOrder.setEditOrderAmount(null);
                    mjOrder.setNewOrderAmount(mjOrder.getEditOrderAmount());
                    mjOrder.setSpareInt1(null);
                    //审核状态21 - 待审核 22 - 已审核 23-已驳回
                    mjOrder.setAuditStatus(1);
                    return this.updateById(mjOrder);
                } else {
                    throw new RuntimeException("该用户无权限审核,请核查!");
                }
            }
        }
        return true;
    }

    @Override
    public boolean refuse(Long id) {
        //流程类型：1-价格设置 2-价格调整
        MjFlowConfig mjFlowConfig = mjFlowConfigService.getOne(new LambdaQueryWrapper<MjFlowConfig>()
                .eq(MjFlowConfig::getFlowType, 2));
        if (mjFlowConfig == null) {
            throw new RuntimeException("调价规则不存在无法审核,请核查!");
        }
        MjOrder mjOrder = this.getById(id);
        if (mjOrder == null) {
            throw new RuntimeException("订单数据不存在,请核查!");
        }
        List<String> roles = Arrays.asList(mjFlowConfig.getRoleCode());
        for (String role : roles) {
            if (MoJiCommonUtils.getRoleCode().contains(role)) {
                mjOrder.setEditOrderAmount(null);
                //审核状态    20 - 待审核 21 - 已审核 22-已驳回
                mjOrder.setAuditStatus(22);
                break;
            }
        }
        return this.updateById(mjOrder);
    }

    @Override
    public MyPage<MjOrder> queryFinanceByPage(QueryOrderDto dto) {
        LambdaQueryWrapper<MjOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(ObjectUtil.isNotEmpty(dto.getOrderCode())
                , MjOrder::getOrderCode, dto.getOrderCode());
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getPayType())
                , MjOrder::getPayType, dto.getPayType());
        if(ObjectUtil.isNotEmpty(dto.getOrderAmount()))
        {
            BigDecimal bigDecimalValue = new BigDecimal(dto.getOrderAmount());
            wrapper.eq(MjOrder::getOrderAmount,bigDecimalValue);
        }
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getOrderName())
                , MjOrder::getOrderName, dto.getOrderName());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getMobile())
                , MjOrder::getMobile, dto.getMobile());
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getBillStatus())
                , MjOrder::getBillStatus, dto.getBillStatus());
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getOrderStatus())
                , MjOrder::getOrderStatus, dto.getOrderStatus());
        //订单时间
        if(ObjectUtil.isNotEmpty(dto.getOrderTime()))
        {
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(dto.getOrderTime());
            String startDate=dateStr+" 00:00:00";
            String endDate=dateStr+" 23:59:59";
            wrapper.ge( MjOrder::getOrderTime
                    , startDate);
            wrapper.le( MjOrder::getOrderTime
                    , endDate);
        }
        //支付时间
        if(ObjectUtil.isNotEmpty(dto.getPayTime()))
        {
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(dto.getPayTime());
            String startDate=dateStr+" 00:00:00";
            String endDate=dateStr+" 23:59:59";
            wrapper.ge( MjOrder::getPayTime
                    , startDate);
            wrapper.le( MjOrder::getPayTime
                    , endDate);
        }
        //日期_开始
        wrapper.ge(ObjectUtil.isNotEmpty(dto.getOrderTimeStart())
                , MjOrder::getOrderTime, dto.getOrderTimeStart());
        //日期_截止
        wrapper.le(ObjectUtil.isNotEmpty(dto.getOrderTimeEnd())
                , MjOrder::getOrderTime, dto.getOrderTimeEnd());
        //创建时间倒叙
        wrapper.orderByDesc(MjOrder::getOrderTime);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<MjOrder> mjOrders = list(wrapper);
        //审核状态
        Map<String, String> map = dataDictionaryService.getMapByDictionaryCode("DDZT");
        if (ObjectUtil.isNotEmpty(mjOrders)) {
            for (MjOrder mjOrder : mjOrders) {
                mjOrder.setBillStatusStr(mjOrder.getBillStatus()==0?"未开":"已开");
                mjOrder.setOrderStatusStr(map.get(mjOrder.getOrderStatus()+""));
                mjOrder.setOrderTimeStr(DateUtils.formatDate(mjOrder.getOrderTime(),DateUtils.DATE_FORMAT));
                if(ObjectUtil.isNotEmpty(mjOrder.getPayTime())){
                    mjOrder.setPayTimeStr(DateUtils.formatDate(mjOrder.getPayTime(),DateUtils.DATE_FORMAT));
                }
            }
        }

        //已付款订单量
        int payOrderCount = 0;
        //总收入
        BigDecimal totalAmount = new BigDecimal(0);
        LambdaQueryWrapper<MjOrder> wrapper1 = new LambdaQueryWrapper<>();
        //日期_开始
        wrapper.ge(ObjectUtil.isNotEmpty(dto.getOrderTimeStart())
                , MjOrder::getOrderTime, dto.getOrderTimeStart());
        //日期_截止
        wrapper.le(ObjectUtil.isNotEmpty(dto.getOrderTimeEnd())
                , MjOrder::getOrderTime, dto.getOrderTimeEnd());
        List<MjOrder> mjOrderList = list(wrapper1);
        if (ObjectUtil.isNotEmpty(mjOrderList)) {
            for (MjOrder mjOrder : mjOrderList) {
                //订单状态0 - 待支付 1 - 已完成 2-已取消
                if (mjOrder.getOrderStatus() == 1) {
                    payOrderCount = payOrderCount + 1;
                    BigDecimal payAmount=ObjectUtil.isEmpty(mjOrder.getPayAmount())?new BigDecimal(0):mjOrder.getPayAmount();
                    totalAmount = totalAmount.add(payAmount);
                }
            }
        }
        PageInfo<MjOrder> info = new PageInfo<>(mjOrders);
        return PageUtil.PageInfo3MyPage(info, mjOrderList.size(), payOrderCount, totalAmount);
    }

    @Override
    public int reportExport(QueryOrderDto dto, HttpServletResponse response) {
        LambdaQueryWrapper<MjOrder> wrapper = new LambdaQueryWrapper<>();
        //日期_开始
        wrapper.ge(ObjectUtil.isNotEmpty(dto.getOrderTimeStart())
                , MjOrder::getOrderTime, dto.getOrderTimeStart());
        //日期_截止
        wrapper.le(ObjectUtil.isNotEmpty(dto.getOrderTimeEnd())
                , MjOrder::getOrderTime, dto.getOrderTimeEnd());
        //创建时间倒叙
        wrapper.orderByDesc(MjOrder::getOrderTime);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<MjOrder> mjOrders = list(wrapper);
        List<FinanceOrderVo> financeOrderVos = new ArrayList<>();
        Map<String, String> map = dataDictionaryService.getMapByDictionaryCode("DDZT");
        if (ObjectUtil.isNotEmpty(mjOrders)) {
            for (MjOrder mjOrder : mjOrders) {
                FinanceOrderVo financeOrderVo = new FinanceOrderVo();
                BeanUtils.copyProperties(mjOrder, financeOrderVo);
                if (ObjectUtil.isNotEmpty(mjOrder.getBillStatus())) {
                    financeOrderVo.setBillStatusStr(mjOrder.getBillStatus() == 0 ? "未开" : "已开");
                    financeOrderVo.setOrderStatusStr(map.get(financeOrderVo.getOrderStatus()+""));
                }
                financeOrderVo.setPayType(mjOrder.getBillStatus() == 0 ? "支付宝" : "微信");
                financeOrderVos.add(financeOrderVo);
            }
        }
        ExcelUtil.exportExcel(financeOrderVos, "报表导出", FinanceOrderVo.class, response);
        return 1;
    }

    @Override
    public Object test() {
        String orderCode = idGenerator.idGenerator("DD");
        return orderCode;
    }

    @Override
    public void cancelOrder() {
        LambdaQueryWrapper<MjOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjOrder::getOrderStatus,0);
        List<MjOrder> mjOrderList = this.list(wrapper);
        if(ObjectUtil.isNotEmpty(mjOrderList)){
            mjOrderList.forEach(mjOrder -> {
                System.out.println("订单创建时间=========="+ DateUtils.formatDate(mjOrder.getCreateTime(),DateUtils.DATETIME_FORMAT));
                long diff= DateUtil.between(new Date(),mjOrder.getCreateTime(), DateUnit.MINUTE);
                System.out.println("时间差值=========="+diff);
                if(diff >=30){
                    mjOrder.setOrderStatus(6);
                    this.updateById(mjOrder);

                    LambdaQueryWrapper<MjOrderDetail> wrapper0 = new LambdaQueryWrapper<>();
                    wrapper0.eq(MjOrderDetail::getOrderCode,mjOrder.getOrderCode());
                    List<MjOrderDetail> mjOrderDetails=mjOrderDetailService.list(wrapper0);
                    mjOrderDetails.forEach(mjOrderDetail -> {
                        mjOrderDetail.setUseStatus(null);
                        mjOrderDetail.setExpirationTime(null);
                        mjOrderDetailService.updateById(mjOrderDetail);
                    });
                    //超时未支付消息通知
                    LambdaQueryWrapper<SysMessage> wrapper1=new LambdaQueryWrapper<>();
                    wrapper1.eq(SysMessage::getBillTypeCode,"2");
                    wrapper1.eq(SysMessage::getBillNo,mjOrder.getId()+"");
                    wrapper1.eq(SysMessage::getMessageType,"4");
                    wrapper1.eq(SysMessage::getReceiveUserId,mjOrder.getCreateId());
                    SysMessage sysMessage0=sysMessageService.getOne(wrapper1);
                    if(sysMessage0 ==null){
                        SysMessage sysMessage=new SysMessage();
                        sysMessage.setReceiveUserId(mjOrder.getCreateId());
                        sysMessage.setSendUserId(mjOrder.getUserCode());
                        sysMessage.setMarkAsRead(0);
                        sysMessage.setMessageTitle("超时未支付");
                        //消息类型 1-发票提醒 2-下单成功 3-待支付提醒4-超时未支付 5-工单回复 6-工单完结 7-服务到期提醒
                        sysMessage.setMessageType("4");
                        sysMessage.setMessageCenter("尊敬的用户您好：您于"+ com.moji.util.DateUtils.formatDate(mjOrder.getCreateTime(), com.moji.util.DateUtils.DATE_FORMAT_EXP1) +"购买的“包年”未及时支付已被关闭，" +
                                "订单编号为："+mjOrder.getOrderCode()+"，如需继续使用服务，请重新下单。如有疑问请联系客服010-84798388转8042!");
                        sysMessage.setBillNo(mjOrder.getId()+"");
                        sysMessage.setBillTypeCode("2");
                        sysMessage.setCreateId(mjOrder.getCreateId());
                        sysMessage.setUpdateId(mjOrder.getCreateId());
                        sysMessage.setCreateTime(new Date());
                        sysMessage.setUpdateTime(new Date());
                        sysMessageService.add(sysMessage);
                    }
                }
            });
        }
    }

    @Override
    public void payOrderNotice() {
        LambdaQueryWrapper<MjOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjOrder::getOrderStatus,0);
        List<MjOrder> mjOrderList = this.list(wrapper);
        if(ObjectUtil.isNotEmpty(mjOrderList)) {
            mjOrderList.forEach(mjOrder -> {
                //待支付消息通知
                LambdaQueryWrapper<SysMessage> wrapper1=new LambdaQueryWrapper<>();
                wrapper1.eq(SysMessage::getBillTypeCode,"2");
                wrapper1.eq(SysMessage::getBillNo,mjOrder.getId()+"");
                wrapper1.eq(SysMessage::getMessageType,"3");
                wrapper1.eq(SysMessage::getReceiveUserId,mjOrder.getCreateId());
                SysMessage sysMessage0=sysMessageService.getOne(wrapper1);
                if(sysMessage0 ==null){
                    SysMessage sysMessage=new SysMessage();
                    sysMessage.setReceiveUserId(mjOrder.getCreateId());
                    sysMessage.setSendUserId(mjOrder.getUserCode());
                    sysMessage.setMarkAsRead(0);
                    sysMessage.setMessageTitle("超时未支付");
                    //消息类型 1-发票提醒 2-下单成功 3-待支付提醒4-超时未支付 5-工单回复 6-工单完结 7-服务到期提醒
                    sysMessage.setMessageType("3");
                    sysMessage.setMessageCenter("尊敬的用户您好：您于"+ com.moji.util.DateUtils.formatDate(mjOrder.getCreateTime(), com.moji.util.DateUtils.DATE_FORMAT_EXP1) +"购买的“包年”服务尚未支付，" +
                            "订单编号为："+mjOrder.getOrderCode()+"，如有疑问请联系客服010-84798388转8042!");
                    sysMessage.setBillNo(mjOrder.getId()+"");
                    sysMessage.setBillTypeCode("2");
                    sysMessage.setCreateId(mjOrder.getCreateId());
                    sysMessage.setUpdateId(mjOrder.getCreateId());
                    sysMessage.setCreateTime(new Date());
                    sysMessage.setUpdateTime(new Date());
                    sysMessageService.add(sysMessage);
                }
            });
        }
    }

    @Override
    public void dueOrderTask() {
        LambdaQueryWrapper<MjOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjOrder::getOrderStatus,1);
        List<MjOrder> mjOrderList = this.list(wrapper);
        if(ObjectUtil.isNotEmpty(mjOrderList)) {
            mjOrderList.forEach(mjOrder -> {
                List<MjOrderDetail> mjOrderDetails=mjOrderDetailService.list(new LambdaQueryWrapper<MjOrderDetail>()
                        .eq(MjOrderDetail::getOrderCode, mjOrder.getOrderCode()));
                mjOrderDetails.forEach(mjOrderDetail -> {
                    String expirationTimeStr=getExpirationTimeStr(mjOrderDetail);
                    System.out.println("服务逾期时间=========="+ DateUtils.formatDate(mjOrderDetail.getExpirationTime(),DateUtils.DATETIME_FORMAT));
                    long diff= DateUtil.between(new Date(),mjOrderDetail.getExpirationTime(), DateUnit.DAY);
                    System.out.println("服务逾期时间差值=========="+diff);
                    if(diff ==1) {
                        //服务到期消息通知
                        LambdaQueryWrapper<SysMessage> wrapper1=new LambdaQueryWrapper<>();
                        wrapper1.eq(SysMessage::getBillTypeCode,"2");
                        wrapper1.eq(SysMessage::getBillNo,mjOrderDetail.getId()+"");
                        wrapper1.eq(SysMessage::getMessageType,"7");
                        wrapper1.eq(SysMessage::getReceiveUserId,mjOrder.getCreateId());
                        SysMessage sysMessage0=sysMessageService.getOne(wrapper1);
                        if(sysMessage0 ==null) {
                            SysMessage sysMessage = new SysMessage();
                            sysMessage.setReceiveUserId(mjOrder.getCreateId());
                            sysMessage.setSendUserId(mjOrder.getUserCode());
                            sysMessage.setMarkAsRead(0);
                            sysMessage.setMessageTitle("服务到期提醒");
                            //消息类型 1-发票提醒 2-下单成功 3-待支付提醒4-超时未支付 5-工单回复 6-工单完结 7-服务到期提醒
                            sysMessage.setMessageType("7");
                            sysMessage.setMessageCenter("尊敬的用户您好：您购买的“包年”服务" + expirationTimeStr + "到期，" +
                                    "订单明细编号为：" + mjOrderDetail.getOrderMxCode() + "，避免影响您使用请及时续费或重新购买，如有疑问请及时联系客服010-84798388转8042！");
                            sysMessage.setBillNo(mjOrder.getId() + "");
                            sysMessage.setBillTypeCode("2");
                            sysMessage.setCreateId(mjOrder.getCreateId());
                            sysMessage.setUpdateId(mjOrder.getCreateId());
                            sysMessage.setCreateTime(new Date());
                            sysMessage.setUpdateTime(new Date());
                            sysMessageService.add(sysMessage);
                        }
                    }
                });
            });
        }
    }

    private String getExpirationTimeStr(MjOrderDetail mjOrderDetail) {
        //服务到期时间
        if (ObjectUtil.isNotEmpty(mjOrderDetail.getServiceTimeCode())) {
            if ("N1Y".equals(mjOrderDetail.getServiceTimeCode())) {
                if (mjOrderDetail.getEffectTime() != null) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(mjOrderDetail.getEffectTime());
                    calendar.add(Calendar.YEAR, 1);
                    mjOrderDetail.setExpirationTime(calendar.getTime());
                    return DateUtils.formatDate(mjOrderDetail.getExpirationTime(), DateUtils.DATE_FORMAT_EXP1);
                }
            } else if ("N2Y".equals(mjOrderDetail.getServiceTimeCode())) {
                {
                    if (mjOrderDetail.getEffectTime() != null) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(mjOrderDetail.getEffectTime());
                        calendar.add(Calendar.YEAR, 2);
                        mjOrderDetail.setExpirationTime(calendar.getTime());
                        return DateUtils.formatDate(mjOrderDetail.getExpirationTime(), DateUtils.DATE_FORMAT_EXP1);
                    }
                }

            } else if ("T7D".equals(mjOrderDetail.getServiceTimeCode())) {
                if (mjOrderDetail.getEffectTime() != null) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(mjOrderDetail.getEffectTime());
                    calendar.add(Calendar.DAY_OF_MONTH, 7);
                    mjOrderDetail.setExpirationTime(calendar.getTime());
                    return DateUtils.formatDate(mjOrderDetail.getExpirationTime(), DateUtils.DATE_FORMAT_EXP1);
                }

            }
        }
        return null;
    }
}
